package com.hengfoxwolf.jetpackdemo.datastore
import android.content.Context
import com.hengfoxwolf.jetpackdemo.constants.StringConstant
import com.hengfoxwolf.jetpackdemo.util.ContextUtil

object SharedPreferenceUtil {

    private val prefs by lazy {
        ContextUtil.getCurrentApplication()
            ?.getSharedPreferences(StringConstant.SHARED_DATA, Context.MODE_PRIVATE)
    }

    fun <V> findValue(name: String, default: V): V = with(prefs) {
        val value: Any? = when (default) {
            is Int -> this?.getInt(name, default)
            is String -> this?.getString(name, default)
            is Boolean -> this?.getBoolean(name, default)
            is Float -> this?.getFloat(name, default)
            is Long -> this?.getLong(name, default)
            else -> throw IllegalArgumentException("Not supported this type.")
        }
         value as V
    }

    fun <V> putValue(name: String, default: V) = with (prefs?.edit()) {
        when (default) {
            is Int -> this?.putInt(name, default)
            is String -> this?.putString(name, default)
            is Boolean -> this?.putBoolean(name, default)
            is Float -> this?.putFloat(name, default)
            is Long -> this?.putLong(name, default)
            else -> throw IllegalArgumentException("Not supported this type.")
        }?.apply()
    }

    fun clear() {
        prefs?.edit()?.clear()?.apply()
    }

    fun removeKey(key: String) {
        prefs?.edit()?.remove(key)?.apply()
    }
}